package com.devo.icecream.modbus

import android.os.Handler
import com.devo.icecream.AppLogger
import com.serotonin.modbus4j.BatchRead
import com.serotonin.modbus4j.ModbusMaster
import com.serotonin.modbus4j.exception.ModbusTransportException
import com.serotonin.modbus4j.locator.BaseLocator

/**
 * 贺杨 这个类的功能主要是查询plc工控机故障的状态
 */
class PLCMalfunction(private val master: ModbusMaster, private val workHandler: Handler) {
    //故障地址
    private val address = mapOf(
        "M2001" to 2001,
        "M2002" to 2002,
        "M2003" to 2003,
        "M2004" to 2004,
        "M2005" to 2005,
        "M2006" to 2006,
        "M2007" to 2007,
        "M2008" to 2008,
        "M2009" to 2009,
        "M2010" to 2010,
        "M2011" to 2011,
        "M2012" to 2012,
        "M2013" to 2013,
        "M2014" to 2014,
        "M2015" to 2015,
        "M2016" to 2016,
        "M2017" to 2017,
        "M2018" to 2018,
        "M2019" to 2019,
        "M2020" to 2020,
        "M2021" to 2021,
        "M2022" to 2022,
        "M2023" to 2023,
        "M2024" to 2024,
        "M2025" to 2025,
    )
    //故障结果
    private val result = mutableMapOf<String, Boolean>()
    //待发送
    private val requests = BatchRead<String>().apply {
        address.forEach { entry ->
            val (k, v) = entry
            addLocator(k, BaseLocator.inputStatus(1, v))
        }
    }

    private fun loopQuery() {
        workHandler.postDelayed({
            query()
            loopQuery()
        }, (5 * 1000).toLong())
    }
    //开始发送查询
    private fun query() {
        try {
            synchronized(PLCMalfunction::class.java) {
                master.trySend(requests)?.let { batchResults ->
                    address.keys.forEach {
                        //将查询结果放到集合中
                        result[it] = batchResults.getValue(it) as Boolean
                    }
                }
            }
        } catch (e: ModbusTransportException) {
            AppLogger.e(e, "查询故障状态报错")
        }

    }

    //获取查询结果
    fun getMalfunctions() = result.filter { it.value }.map { it.key }.toList()

    init {
        loopQuery()
    }
}